package org.cable.account.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.cable.account.component.SmsComponent;
import org.cable.account.config.SmsConfig;
import org.cable.account.service.NotifyService;
import org.cable.common.constants.RedisKey;
import org.cable.common.enums.BizCodeEnum;
import org.cable.common.enums.SendCodeEnum;
import org.cable.common.util.CheckUtil;
import org.cable.common.util.CommonUtil;
import org.cable.common.util.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import sun.nio.cs.US_ASCII;

import java.util.concurrent.TimeUnit;

/**
 * @author hsj
 * @date 2023/10/26 10:10
 */
@Service
@Slf4j
public class NotifyServiceImpl implements NotifyService {


    private static final long CODE_EXPIRED = 60 * 1000 ;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SmsComponent smsComponent;

    @Autowired
    private SmsConfig smsConfig;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    @Async("threadPoolTaskExecutor")
    public void testSend() {

        try {
            TimeUnit.MILLISECONDS.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        ResponseEntity<String> forEntity = restTemplate.getForEntity("", String.class);
        String body = forEntity.getBody();
        log.info("body:  " + body);

    }


    @Override
    public JsonData sendCode(SendCodeEnum userRegister, String target) {

        String cacheKey = String.format(RedisKey.CHECK_CODE_KEY, userRegister.name(), target);

        String cacheValue = redisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isNotBlank(cacheValue)){
            long ttl = Long.parseLong(cacheKey.split("_")[1]);
            long leftTime =  CommonUtil.getCurrentTimestamp() -ttl;
            if (leftTime < (1000*60)){
                log.info("重复发送短信验证码,时间间隔为：{}秒",leftTime);
                return JsonData.buildResult(BizCodeEnum.CODE_LIMITED);
            }
        }

        String code = CommonUtil.getRandomCode(6);
        String value = code + "_" + CommonUtil.getCurrentTimestamp();
        redisTemplate.opsForValue().set(cacheKey,value,CODE_EXPIRED,TimeUnit.MILLISECONDS);
         if (CheckUtil.isPhone(target)){
             smsComponent.send(target,smsConfig.getTemplateId(),code);
         }
         if (CheckUtil.isEmail(target)){
             //todo: 邮箱发送
         }
        return JsonData.buildSuccess();
    }


    @Override
    public boolean checkCode(SendCodeEnum sendCodeEnum, String target, String code) {

        String cacheKey = String.format(RedisKey.CHECK_CODE_KEY, sendCodeEnum.name(), target);
        String cacheValue = redisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isNotBlank(cacheValue)){
           String cacheCode =  cacheValue.split("_")[0];
           if (cacheCode.equalsIgnoreCase(code)){
               redisTemplate.delete(cacheCode);
               return true;
           }
        }
        return false;
    }
}
